package com.fly.demo.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.time.DateFormatUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * HttpServlet实现SSE
 */
@Slf4j
@WebServlet(value = "/servlet/sse", asyncSupported = true)
public class SseServlet extends HttpServlet
{
    private static final long serialVersionUID = -8436396456112677485L;
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        response.setContentType("text/event-stream");
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        AsyncContext asyncContext = request.startAsync();
        asyncContext.setTimeout(0); // 默认30秒，0或负值表示不超时
        
        long initialDelay = 10000L - System.currentTimeMillis() % 10000L - 1; // 计算延迟（微调1ms），保证准时启动
        log.info("initialDelay {} Seconds", initialDelay / 1000.0);
        PrintWriter writer = asyncContext.getResponse().getWriter();
        new ScheduledThreadPoolExecutor(10).scheduleAtFixedRate(() -> {
            writer.write("data:" + DateFormatUtils.format(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss") + "\r\n\r\n");
            if (writer.checkError())
            {
                log.info("结束连接");
                return;
            }
        }, initialDelay, 10000L, TimeUnit.MILLISECONDS);
    }
}
